<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Grid\CustomerBatchAllot;
use App\Admin\Actions\Grid\CustomerBatchOoaInto;
use App\Admin\Actions\Grid\CustomerBatchOoaReceive;
use App\Admin\Actions\Show\CustomerOoaInto;
use App\Admin\Actions\Show\CustomerReceive;
use App\Models\Community;
use App\Models\Customer;
use App\Traits\CustomerCard;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Layout\Column;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Widgets\Card;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Admin;
use App\Admin\Extensions\FilterAwareNavigation;
use App\Admin\Actions\Show\CustomerFollowup;



class CustomerController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @param   integer     $uri_type   1 客户列表  2 公海 3 我的客户
     *
     * @return Grid
     */
    protected function grid($uri_type = 1)
    {
        return Grid::make(Customer::with(['property.community']), function (Grid $grid)  use ($uri_type){
            $grid->column('id');
            $grid->column('phone')->display(function ($value) use ($uri_type){
                $params = request()->all();
                $params['uri_type'] = $uri_type;
                return detialsLink('customer/' . $this->id . '?' . http_build_query($params), $value);
            });
            $grid->column('name');
            $grid->column('property','楼盘名称')->display(function ($property) {
                return collect($property)->map(function ($item){
                    if (isset($item['community']) && !empty(isset($item['community']))){
                        return $item['community']['community_name'];
                    }
                })->implode('-');
            });
            $grid->column('status')->using(Customer::STATUS)->badge([
                100 =>  'red',
                101 =>  'yellow',
                102 =>  'green',
                103 =>  'gray',
            ]);
            $grid->column('level')->using(Customer::LEVEL)->badge([
                100 =>  'gray',
                101 =>  'red',
                102 =>  'yellow',
                103 =>  'green',
                104 =>  'blue',
            ]);
            $grid->column('followup','跟进记录')->display(function ($followups) {
                return $followups->take(3)->map(function ($followups) {
                    return "<div>{$followups->content}</div>";
                })->implode('');
            });
            $grid->column('last_note_time');

            $grid->selector(function (Grid\Tools\Selector $selector) {
                $selector->selectOne('status', '状态', Customer::STATUS);
                $selector->selectOne('level', '意向级别', Customer::LEVEL);

            });
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('property.community_id','楼盘名称')->select(Community::all()->pluck('community_name','id'));
                $filter->like('phone');
                $filter->like('name');

            });

            $grid->model()->orderBy('id','desc');

            $grid->disableCreateButton();
            $grid->disableActions();
            if ($uri_type == 1){
                //$grid->batchActions([new CustomerBatchAllot()]);
            }elseif ($uri_type == 2){
                $grid->model()->where('user_id',0);
                //$grid->batchActions([new CustomerBatchAllot()]);
                $grid->batchActions([new CustomerBatchOoaReceive()]);
            }elseif ($uri_type == 3){
                $grid->model()->where('user_id',Admin::user()->id);
                $grid->batchActions([new CustomerBatchOoaInto()]);
            }

        });
    }

    public function show($id, Content $content)
    {
        return $content
            ->title($this->title())
            ->description($this->description()['index'] ?? trans('admin.show'))
            ->body(function (Row $row) use ($id) {
                $row->column(6, function (Column $column) use ($id) {
                    $column->row($this->detail($id));
                    $column->row(new Card('流转记录', CustomerCard::hasCustomerAssignmentCard($id)));
                });
                $row->column(6, function (Column $column) use ($id) {
                    $column->row(new Card('关联房源', CustomerCard::hasCustomerPropertyCard($id)));
                    $column->row(new Card('跟进记录', CustomerCard::hasCustomerFollowupCard($id)));
                });
            });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, Customer::with([]), function (Show $show) use ($id){
            $show->field('id');
            $show->field('phone');
            $show->field('name');
            //$show->field('gender')->using(Customer::GENDER);
            $show->field('status')->using(Customer::STATUS);
            $show->field('level')->using(Customer::LEVEL);
            //$show->field('type');

            //$show->field('email');
            //$show->field('id_card');
            //$show->field('address');
            //$show->field('source_id');
            //$show->field('budget_min');
            //$show->field('budget_max');
            //$show->field('preferred_property_type');
            //$show->field('preferred_region_ids');
            //$show->field('notes');

            $show->disableEditButton();

            $show->tools(new CustomerFollowup());
            // 获取当前模型
            $model = Customer::findOrFail($id);
            // 获取列表页的所有查询参数
            $queryParams = request()->all();
            // 添加导航按钮
            $show->panel()->tools(function ($tools) use ($model, $queryParams) {
                // 构建基础查询
                $builder = Customer::query();
                // 应用列表页的筛选条件
                $this->applyFilters($builder, $queryParams);
                // 获取上一页记录
                $prev = FilterAwareNavigation::getAdjacentRecord($builder, $model, $queryParams, 'prev');
                // 获取下一页记录
                $next = FilterAwareNavigation::getAdjacentRecord($builder, $model, $queryParams, 'next');
                // 添加上一页按钮
                if ($prev) {
                    $tools->append(FilterAwareNavigation::getTurnPageButton('customer/' . $prev->id, $queryParams, 'prev'));
                }
                // 添加下一页按钮
                if ($next) {
                    $tools->append(FilterAwareNavigation::getTurnPageButton('customer/' . $next->id, $queryParams, 'next'));
                }
            });
            if (isset($queryParams['uri_type'])){
                if ($queryParams['uri_type'] == 2){
                    $show->tools(new CustomerReceive());
                }elseif ($queryParams['uri_type'] == 3){
                    $show->tools(new CustomerOoaInto());
                }
            }


        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Customer(), function (Form $form) {
            $form->display('id');
            $form->text('phone');
            $form->text('name');
            $form->radio('gender')->options(Customer::GENDER);
            $form->radio('status')->options(Customer::STATUS);
            $form->radio('level')->options(Customer::LEVEL);
            //$form->currency('budget_min');
            //$form->currency('budget_max');
            //$form->text('email');
            //$form->text('id_card');
            //$form->select('source_id');
            //$form->text('type');
            //$form->text('address');


        });
    }


    //公海客户
    public function ooaList(Content $content)
    {
        return $content
            ->translation($this->translation())
            ->title('公海')
            ->description('公海列表')
            ->body($this->grid(2));
    }

    //我的客户
    public function myList(Content $content)
    {
        return $content
            ->translation($this->translation())
            ->title('我的客户')
            ->description('我的客户')
            ->body($this->grid(3));
    }


    /**
     * 应用列表页的筛选条件
     */
    protected function applyFilters($builder, $queryParams)
    {
        // 处理搜索条件
        $selector  = $queryParams['_selector'] ?? [];
        if(isset($queryParams['uri_type'])){
            if ($queryParams['uri_type'] == 2){
                $builder->where('user_id',0);
            }elseif ($queryParams['uri_type'] == 3){
                $builder->where('user_id',Admin::user()->id);
            }
        }
        $builder->andFilterWhere('status', $selector['status'] ?? '')
            ->andFilterWhere('level', $selector['level'] ?? '');
        if(isset($queryParams['name']) && !empty($queryParams['name'])){
            $builder->where('name','like','%' . $queryParams['name'] . '%');
        }
        if(isset($queryParams['phone']) && !empty($queryParams['phone'])){
            $builder->where('phone','like','%' . $queryParams['phone'] . '%');
        }
        if (isset($queryParams['phone']) && !empty($queryParams['property'])) {
            $builder->whereHas('property', function ($q) use ($queryParams){
                $q->where('community_id', $queryParams['property']['community_id']);
            });
        }
        // 处理范围筛选
        if (!empty($queryParams['_scope_'])) {
            //$builder->{$queryParams['_scope_']}();
        }

    }
}
